package me.zhengjie.modules.system.repository

import me.zhengjie.modules.system.domain.Dept
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query

/**
 * @author Kuki Wu
 * @date 2019-03-25
 */
interface DeptRepository : JpaRepository<Dept?, Long?>, JpaSpecificationExecutor<Dept?> {
    fun findByPid(id: Long?): List<Dept?>?

    @Query(value = "select name from sys_dept where id = ?1", nativeQuery = true)
    fun findNameByIdNotNull(id: Long?): String?

    fun findByRoles_Id(id: Long?): Set<Dept?>?

    /**
     * 获取顶级部门
     * @return /
     */
    fun findByPidIsNull(): List<Dept?>?

    /**
     * 根据角色ID 查询
     * @param roleId 角色ID
     * @return /
     */
    @Query(
        value = "select d.* from sys_dept d, sys_roles_depts r where " +
                "d.dept_id = r.dept_id and r.role_id = ?1", nativeQuery = true
    )
    fun findByRoleId(roleId: Long?): Set<Dept?>?

    /**
     * 判断是否存在子节点
     * @param pid /
     * @return /
     */
    fun countByPid(pid: Long?): Int

    /**
     * 根据ID更新sub_count
     * @param count /
     * @param id /
     */
    @Modifying
    @Query(value = " update sys_dept set sub_count = ?1 where dept_id = ?2 ", nativeQuery = true)
    fun updateSubCntById(count: Int?, id: Long?)
}